//index.js
//获取应用实例
var WxSearch = require('../wxSearchView/wxSearchView.js');

const app = getApp()
Page({
  data: {
    wordContent: '',
    dkheight: 50,
    activeNames: 1,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    info: '',
    hotContent: {},
    dkcontent: "",
    dkcontent2: "",
    showIcon: true,
    show: false,
    arx: 320,
    touchS: [0, 0],
    wxSearchData: '',
    touchE: [0, 0],
    hotkeys: [],
    autokeys: [],
  },

  touchStart: function(e) {
    // console.log(e.touches[0].pageX)
    let sx = e.touches[0].pageX
    let sy = e.touches[0].pageY
    this.data.touchS = [sx, sy]
  },
  touchMove: function(e) {
    let sx = e.touches[0].pageX;
    let sy = e.touches[0].pageY;
    this.data.touchE = [sx, sy]
  },
  touchEnd: function(e) {
    let _this = this
    let start = this.data.touchS
    let end = this.data.touchE
    console.log(start)
    console.log(end)
    if (start[1] < end[1] - 2) {
      // console.log('下滑')
      _this.setData({
        showIcon: true
      })
    } else if (start[1] > end[1] + 1) {
      // console.log('上滑')
      _this.setData({
        showIcon: false
      })
    } else {
      _this.setData({
        showIcon: !_this.data.showIcon
      })
    }
  },
  // http://www.godic.net/dicts/de/m%c3%bcde?recordid=MjQwNDQw recordid=MjM3NDMy MjIzODIx
  onShow() {
    let _this = this
    let len = wx.getStorageSync('wxSearchHisKeys').length
    if (len > 0 && len < 5) {
      _this.setData({
        arx: 400
      })
    } else if (len > 4) {
      _this.setData({
        arx: 500
      })
    }
    let temData = _this.data.temData
    if (temData == undefined) {
      temData = {}
    }
    temData.tipKeys = [];
    // 更新视图
    _this.setData({
      wxSearchData: temData
    })
  },
  onLoad: function(param) {
    let _this = this
    if (wx.getStorageSync("readindex") != 1) {
      wx.showModal({
        title: '#船新版本V3.0.1 Beta',
        content: '【查词记录】、【查词联想】试用版 -02.08.19',
        success(res) {
          if (res.confirm) {
            wx.setStorageSync("readindex", 1)
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
    if (wx.getStorageSync("admin") == 1) {
      _this.setData({
        show: true
      })
    }
    wx.hideNavigationBarLoading()
    // 获得高度
    let winPage = this;
    let userInfo = app.getGlobalUserInfo()
    console.log('global', userInfo)
    this.setData({
      userInfo: userInfo,
      param: param
    })
    console.log('page:', param)
    console.log('userInfo:', _this.data.userInfo)
    if (param.page != undefined) {
      let page = param.page
      if (param.share != undefined) {
        page += `&share=${param.share}`
      }
      if (param.title != undefined) {
        page += `&title=${param.title}`
      }
      if (param.type != undefined) {
        page += `&type=${param.type}`
      }
      this.setData({
        page: page
      })

      console.log('page', decodeURIComponent(page.replace('webview@', 'webview?').replace('article@', 'article?').replace('video@', 'video?')))

    }
    console.log('session', this.data.userInfo)
    wx.getSystemInfo({
      success: function(res) {
        let winHeight = res.windowHeight;
        console.log(winHeight);
        winPage.setData({
          dkheight: winHeight - winHeight * 0.05 - 80
        })
      }
    })
    console.log("app.getGlobalUserInfo().userId", app.getGlobalUserInfo().userId)
    if (app.getGlobalUserInfo().userId != undefined) {
      this.getHot()

      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.userInfo']) {
            _this.wxLogin()
          }
        }
      })

    }

  },
  // 3 转发函数，固定部分，直接拷贝即可
  wxSearchInput: WxSearch.wxSearchInput, // 输入变化时的操作
  setAuto: WxSearch.setAuto, // 自动数组
  wxSearchKeyTap: WxSearch.wxSearchKeyTap, // 点击提示或者关键字、历史记录时的操作
  wxSearchDeleteAll: WxSearch.wxSearchDeleteAll, // 删除所有的历史记录
  wxSearchConfirm: WxSearch.wxSearchConfirm, // 搜索函数
  wxSearchClear: WxSearch.wxSearchClear, // 清空函数
  getHisKeys: WxSearch.getHisKeys,

  wxSearchInput(e) {
    let _this = this
    let temData = {}
    let info = e.detail.value;
    temData.hotkeys = _this.data.hotkeys;
    _this.setData({
      info: info
    })
    console.log("ss", wx.getStorageSync('wxSearchHisKeys').length)
    if (wx.getStorageSync('wxSearchHisKeys').length > 0) {
      _this.setData({
        arx: _this.data.arx + 100
      })
    }
    wx.request({
      url: `https://www.godic.net/dicts/prefix/${e.detail.value}`,
      method: 'get',
      success: function(res) {
        wx.hideNavigationBarLoading()
        if (res.data.length != 0) {
          temData.tipKeys = res.data.map((item) => {
            return item.value + ' -> ' + item.label
          })
          _this.setData({
            wxSearchData: temData
          })
        }
      },

    })
    console.log('e', _this.data.wxSearchData)

  },

  // 4 搜索回调函数  
  mySearchFunction: function(value) {
    console.log('value,', value)
    if (value == '') {
      wx.showToast({
        title: '请先输入单词',
        icon: 'none'
      })
      return false
    }
    wx.navigateTo({
      url: `../detail/detail?word=${value}`,
    })
  },

  // 5 返回回调函数
  myGobackFunction: function() {
    // do your job here
    // 示例：返回
    wx.redirectTo({
      url: '../index/index?searchValue=返回'
    })
  },
  qq() {
    wx.navigateTo({
      url: '../ex/ex',
    })
  },
  learn() {
    wx.navigateTo({
      url: '../detail/detail',
    })
  },
  imgExists: function(e) {

    //默认图片  
    var imgUrl = "2.jpg";
    var img = event.srcElement;
    img.src = imgUrl;
    console.log(img);
    //判断图片大小是否大于0 或者 图片高度与宽度都大于0
    if (img.filesize > 0 || (img.width > 0 && img.height > 0)) {
      e.src = imgUrl;
    } else {
      //默认图片也不存在的时候
    }
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  bindGetUserInfo() {
    let _this = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          wx.authorize({
            scope: 'scope.userInfo',
            success() {
              _this.wxLogin()
              _this.getHot()
            }
          })
        } else {
          wx.showLoading({
            title: '加载中...',
          })
          wx.getUserInfo({
            success(res) {
              console.log('rooooooooo', res)
              _this.wxLogin()
              _this.getHot(1)

            }
          })
        }
      }
    })
  },
  wxLogin() {
    let _this = this
    wx.login({
      success(res) {
        _this.setData({
          id: res.code
        })
        wx.getSetting({
          success: function(ret) {

            wx.getUserInfo({
              lang: "zh_CN",
              withCredentials: true,
              success: function(info) {
                console.log('res', info)
                let s = JSON.parse(info.rawData)
                if (s.nickName != null && s.avatarUrl != null) {
                  let avatar = s.avatarUrl
                  avatar = s.avatarUrl == '' ? 'http://zzuisa.cn/unlogin.png' : s.avatarUrl
                  wx.request({
                    url: app.serverUrl + `/user/member/wxlogin`,
                    method: 'post',
                    data: {
                      code: res.code,
                      name: s.nickName,
                      headerImg: avatar,
                      gender: s.gender,
                      province: s.province,
                      city: s.city,
                    },
                    success: function(reso) {
                      wx.hideNavigationBarLoading()
                      console.log('resooo', reso)
                      if (reso.data.code == 0) {
                        console.log("qqqqqqwrewr", reso.data.content.headImg.indexOf('vi_32'))

                        if (reso.data.content.headImg.indexOf('vi_32') == -1) {
                          _this.setData({
                            show: false
                          })
                        } else {
                          wx.setStorageSync("admin", 1)
                          _this.setData({
                            show: true
                          })
                        }
                        _this.setData({
                          userInfo: reso.data.content
                        })
                        app.setGlobalUserInfo(reso.data.content)
                        app.globalData.header.Cookie = reso.header["Set-Cookie"];
                        wx.hideLoading()
                        console.error("app.globalData.header.Cookie", app.globalData.header.Cookie)
                        if (_this.data.page != undefined) {
                          let page = _this.data.page
                          _this.toPage()
                        }

                      }

                    }
                  })
                }

              }
            })
          }
        })
      }
    })
  },
  toPage() {
    let _this = this
    let _url = decodeURIComponent(_this.data.page.replace('webview@', 'webview?').replace('article@', 'article?').replace('video@', 'video?'))
    wx.navigateTo({
      url: _url
    })
  },
  moveToLocation() {
    wx.navigateTo({
      url: '/pages/bilibili/bilibili',
    })
  },
  onPullDownRefresh: function() {
    let _this = this
    _this.wxLogin()
    _this.getHot()
  },
  onChange(e) {
    console.log('ee', e.detail)
    this.setData({
      info: e.detail
    })
  },
  onSearch(e) {
    if (this.data.info == undefined || this.data.info == '') {
      wx.showToast({
        title: '请先输入单词',
        icon: 'none'
      })
      return false
    }

    console.log('infoff', this.data.info)
    wx.navigateTo({
      url: `../detail/detail?word=${this.data.info}`,
    })
  },

  toDetail(e) {
    wx.navigateTo({
      url: `../detail/detail?word=${this.data.hotContent.hot[e.target.dataset.arrindex]}`,
    })
  },
  toVideo(e) {
    let _this = this
    let entity = this.data.hotContent.ting[e.target.dataset.arrindex]
    let _url = encodeURIComponent(entity.url)
    if (_this.data.show == true) {
      wx.navigateTo({
        url: `../video/video?url=${_url}&name=${entity.title}`,
      })
    } else {
      wx.showToast({
        title: '正在开发中...',
        icon: 'none'
      })
    }

  },
  getHot(er) {
    wx.showLoading({
      title: '努力加载中...',
    })
    let serverUrl = app.serverUrl
    let _this = this
    let url = `${serverUrl}/dic/hot`
    console.log("er", er)
    // let url = `http://localhost:888/dic/hot`
    wx.request({
      header: app.globalData.header,
      url: url,
      method: "GET",
      success: function(res) {
        console.log('resrrrrr', res)
        if (res.data.code == 0) {
          wx.hideLoading()
          console.log('htot', _this.data.hotContent)
          // wxparse.wxParse('dkcontent', 'html', res.data.content, this, 5);
          let temData = {}
          temData.hotKeys = res.data.content.hot.slice(0, 8);
          let value = wx.getStorageSync('wxSearchHisKeys')
          let len = value.length > 7 ? 7 : value.length
          temData.his = value.slice(0, len);
          let hot = res.data.content
          if (er != 1 && _this.data.show != true) {
            hot.ting = []
          }
          _this.setData({
            hotContent: hot,
            hotkeys: res.data.content.hot,
            temData: temData
          })
        }
        WxSearch.init(
          _this, // 本页面一个引用
          _this.data.hotkeys.slice(0, 8), // 热点搜索推荐，[]表示不使用
          _this.data.autokeys, // 搜索匹配，[]表示不使用
          _this.mySearchFunction, // 提供一个搜索回调函数
          _this.myGobackFunction //提供一个返回回调函数
        );
      },
      fail(e) {
        console.log('e', e)
      }
    })
  },
  onShareAppMessage() {},
})